/**
 * Created by Administrator on 2017/4/19.
 */
import sel from '../../../../index.js';

export default {
  init: function () {
    sel.app.controller('api5C',['$scope',"$http",function ($scope, $http) {
      $scope.title= 'api5';
      var pad = d3.select('.container').append('svg').append('g').attr('class','all');
      var zoom =d3.zoom().on('zoom',function () {
        pad.attr('transform', d3.event.transform)
      });
      d3.select('svg').call(zoom);
      var lines = d3.forceLink()
      .distance(50)
      .strength(1)
      ;
      var force = d3.forceSimulation([{}]).force("link", lines)
                   .force("center", d3.forceCenter(200, 200))
                   .force("charge",  d3.forceManyBody().strength(-300).theta(1))

      ;
      var nodes = force.nodes();
      force.on('tick',function () {
        pad.selectAll('.nodes')
          .attr('transform', function (d) {
            return 'translate(' + d.x + ',' + d.y + ')';
          }).on('dblclick', function (d) {
            d.fx = null;
            d.fy = null;
          })
        ;
        pad.selectAll('.lines')
          .attr('x1',function (d) {
            return d.source.x
          }).attr('x2',function (d) {
            return d.target.x
          }).attr('y1',function (d) {
            return d.source.y
          }).attr('y2',function (d) {
            return d.target.y
          })
        ;
      });
      var links = lines.links();

      var drag_line = pad.append("line")
          .attr("class", "drag_line")
          .attr('stroke','#ff7f0e')
          .attr("x1", 0)
          .attr("y1", 0)
          .attr("x2", 0)
          .attr("y2", 0)
      ;


      function dragstart() {
        d3.select(this).attr('fill','#ff7f0e');
      }
      function dragging(d) {
        drag_line
        .attr("x1", d.x)
        .attr("y1", d.y)
        .attr("x2", d3.event.x)
        .attr("y2",d3.event.y)
        ;
      }
      function dragged() {
        drag_line
        .attr("x1", 0)
        .attr("y1", 0)
        .attr("x2", 0)
        .attr("y2",0)
        ;
        d3.select(this).attr('fill','#000');
        var node = { x:d3.event.x , y:d3.event.y,index :0};
        var sel = d3.select(this).datum();
        links.push({source:sel,target:node});
        lines.links(links);
        nodes.push(node);
        force.nodes(nodes);
        draw();
      }
      var dragEvent = d3.drag().on('start',dragstart).on('drag',dragging).on('end',dragged);


      var i = 0;
      function draw () {
        var nodeG = pad.selectAll('.nodes').data(nodes);
        var lineG = pad.selectAll('.lines').data(links);
        lineG.enter().insert("line",'.nodes').attr('class','lines').attr('stroke','#999').attr('strokeWidth',2);
        nodeG.enter().append('circle').attr('class','nodes').attr('r',5).call(dragEvent);
        nodeG.exit().remove();
        force.alphaTarget(0.3).restart(0.1);
      };
      draw();

    }])
  }
};